<template>
  <el-dialog
    title="机构选择"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="clearDataList()"
    width="85vw"
    top="5vh"
    append-to-body
  >
    <el-container>
      <el-main style="height: 70vh; overflow-x: hidden">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="5">
            <div class="boxsty">
              <el-tree
                ref="treeSelect"
                :data="treeData"
                @check="handleCheckChange"
                show-checkbox
                check-strictly
                :props="defaultProps"
                :filter-node-method="filterNode"
                class="filter-tree"
                node-key="id"
                highlight-current
                :default-expanded-keys="[1]"
                accordion
                @node-click="getNodeData"
                v-loading="loading"
              >
                <span class="custom-tree-node" slot-scope="{ node, data }">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="无数据权限"
                    placement="right-start"
                    v-if="data.isLock"
                  >
                    <span>{{ node.label }} <i class="el-icon-lock"></i></span>
                  </el-tooltip>
                  <span v-if="data.isLock == false">{{ node.label }}</span>
                </span>
              </el-tree>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="8">
            <div class="boxsty" v-if="showPrise">
              <div class="flex titbottom">
                <el-input
                  v-model="listQuery.name"
                  placeholder="请输入搜索用户"
                  style="margin-right: 10px"
                ></el-input>

                <el-button
                  @click="btnSearch"
                  type="primary"
                  icon="el-icon-search"
                  plain
                  >搜索</el-button
                >
              </div>
              <div class="avue-crud">
                 <!-- @row-click="handleClick" -->
                <el-table
                 
                  :data="tableDataDept"
                  v-loading="tableloading"
                  @selection-change="handleClick"
                  :row-key="getRowKeys"
                  style="width: 100%"
                >
                  <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    width="55">
                  </el-table-column>
                  <el-table-column
                    prop="lly"
                    label="联络员"
                    width="80"
                  ></el-table-column>
                  <el-table-column
                    prop="username"
                    label="用户"
                    width="100"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <el-table-column
                    prop="ryName"
                    label="姓名"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                </el-table>
              </div>
              <div style="margin-top: 20px">
                <el-pagination
                  @size-change="sizeChangeHandle"
                  @current-change="currentChangeHandle"
                  :current-page="page.currentPage"
                  :page-sizes="[10, 20, 50, 100]"
                  :page-size="page.pageSize"
                  :total="page.total"
                  background
                  layout="total, sizes, prev, pager, next"
                >
                </el-pagination>
              </div>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="11">
            <div class="boxsty">
              <div class="tabletext titbottom">已选择机构</div>
              <div class="avue-crud">
                <el-table
                  :data="lastPage == 'ndts' ? tableDataOrgSingle : tableDataOrg"
                  ref="jg-table"
                  stripe
                >
                  <el-table-column
                    prop="deptName"
                    label="部门"
                    min-width="220"
                  ></el-table-column>
                  <el-table-column
                    v-if="lastPage == 'ndcj'"
                    prop="ryName"
                    label="联络员"
                    width="100"
                  ></el-table-column>
                  <el-table-column fixed="right" label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button
                        plain
                        @click="delOrgList(scope.$index, scope.row.deptId)"
                        type="danger"
                        plain
                        >删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="tabletext titbottom" style="margin-top: 20px">
                已选择人员
              </div>
              <div class="avue-crud">
                <el-table :data="tableDataUser" ref="ry-table" stripe>
                  <el-table-column
                    prop="deptName"
                    label="部门"
                    width="120"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <el-table-column
                    prop="lly"
                    label="联络员"
                    width="80"
                  ></el-table-column>
                  <el-table-column
                    prop="username"
                    label="用户"
                    width="100"
                  ></el-table-column>
                  <el-table-column
                    prop="ryName"
                    label="姓名"
                    :show-overflow-tooltip="true"
                  ></el-table-column>
                  <el-table-column label="操作" width="100">
                    <template slot-scope="scope">
                      <el-button
                        plain
                        @click="delUserList(scope.$index)"
                        type="danger"
                        plain
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div v-if="lastPage == 'ndts2'" style="margin-top: 20px">
                <div>
                  <el-checkbox v-model="checked1" label="发约人"></el-checkbox>
                  <el-checkbox v-model="checked2" label="受约人"></el-checkbox>
                </div>
              </div>
              <div v-if="lastPage == 'rwsndts'" style="margin-top: 20px">
                <el-checkbox v-model="bkhr" label="被考核人"></el-checkbox>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
    <span slot="footer" class="dialog-footer">
      <el-button plain type="primary" v-if="canSubmit" @click="btnSave"
        >确定</el-button
      >
      <el-button type="primary" plain @click="btnCancel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import store from "@/store";
import { fetchTree } from "@/api/admin/dept";
import { fetchUserList } from "@/api/hetongrenwu/hetongyeji/hetongnd";
import { validatenull } from "@/util/validate";

export default {
  data() {
    return {
      token: "",
      type: "",
      qjDeptId: "", //全局部门id
      qjGzId: "", //全局规则id
      tableloading: false, //table遮挡
      showPrise: true,
      showRentPrise: true,
      visible: false,
      canSubmit: false,
      tableDataDept: [],
      tableDataUser: [],
      tableDataOrg: [],
      tableDataOrgSingle: [],
      ids: [],
      dataForm: {},
      listQuery: {
        name: "",
      },
      loading: false,
      treeData: [],
      jgtreeData: [],
      defaultProps: {
        children: "children",
        label: "name",
        disabled: function (data, node) {
          if (data.isLock == true) {
            return true;
          }
        },
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false, // 是否倒序
      },
      searchForm: {},
      zdySearchForm: {},
      nodeKey: [],
      lastPage: "",
      selectOrgId: [],
      checked1: false,
      checked2: false,
      bkhr: false,
      multipleSelection:[]
    };
  },
  watch: {
    tableDataOrg: {
      handler(newVal) {
        if (this.$refs.treeSelect) {
          this.selectOrgId = newVal.map((item) => item.deptId);
          this.$refs.treeSelect.setCheckedKeys(this.selectOrgId);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {},
  methods: {
    init(id, type, jsonData, lastPage) {
      this.token = store.getters.access_token;
      this.type = type;
      this.qjGzId = id;
      this.ids = jsonData;
      this.visible = true;
      this.canSubmit = true;
      this.lastPage = lastPage;
      //this.loadTableDataUser(id);
      this.getList();
      this.clearDataList();
      this.checked1 = false;
      this.checked2 = false;
      this.bkhr = false;
    },
    getList() {
      this.loading = true;
      fetchTree().then((response) => {
        this.treeData = response.data.data;
        setTimeout(() => {
          this.$refs.treeSelect.filter(false);
          this.loading = false;
        }, 1500);
        this.showPrise = true; // 机构人员显示
        this.showRentPrise = false; // 机构隐藏
      });
    },
    jiequ(data) {
      const result = data.map((item) => {
        const children = item.children.map((every) => {
          return {
            id: every.id,
            parentId: every.parentId,
            name: every.name,
            deptName: every.deptName,
            deptCode: every.deptCode,
            isLock: every.isLock,
          };
        });
        return {
          ...item,
          children: children,
        };
      });
      return result;
    },
    filterNode(value, data) {
      return data.isLock == value;
    },
    getPersons(page, params, selectOrg) {
      this.tableloading = true;
      fetchUserList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm,
          this.zdySearchForm
        )
      )
        .then((response) => {
          this.tableDataDept = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableloading = false;
          if (selectOrg) {
            //选择机构
            const obj = this.tableDataDept.find((item) => item.lly == "是");
            const arr = this.tableDataDept.filter((item) => item.lly == "是");
            if (obj && arr.length > 0) {
              this.$message.closeAll();
              if (this.lastPage == "ndcj") {
                this.tableDataUser = [];
                this.tableDataOrg = [];
                this.tableDataOrgSingle = [];
                this.selectOrgId = [];
              }
              this.$refs.treeSelect.setCheckedKeys([]);
              //tableDataOrgSingle用于在指标拟定的时候显示在页面（同一个机构有多个联络员只显示一个联络员的数据）；tableDataOrg是真正用于传值的数据
              const index = this.tableDataOrgSingle.findIndex(
                (item) => item.userId == obj.userId
              );
              if (index == -1) {
                this.tableDataOrgSingle.push(obj);
                this.unique(this.tableDataOrgSingle);
              }
              arr.forEach((arrObj) => {
                const index = this.tableDataOrg.findIndex(
                  (item) => item.userId == arrObj.userId
                );
                if (index == -1) {
                  this.selectOrgId.push(this.qjDeptId);
                }
              });
              this.tableDataOrg.push(arr[0]);
              this.unique(this.tableDataOrg);
            } else {
              this.$message.closeAll();
              this.$message.warning("请给该单位配置联络员或请选择人员！");
            }
            this.$refs.treeSelect.setCheckedKeys(this.selectOrgId);
          }
        })
        .catch((err) => {
          this.tableloading = false;
        });
    },
    getNodeData(data) {
      if (this.type != "jg") {
        this.page.currentPage = 1;
        this.qjDeptId = data.id;
        this.getPersons(this.page, {
          deptId: data.id,
        });
      } else {
        this.handleClick(data);
      }
    },
    handleCheckChange(data, checked) {
      if (checked.checkedKeys.indexOf(data.id) > -1) {
        if (this.type != "jg") {
          this.page.currentPage = 1;
          this.qjDeptId = data.id;
          this.getPersons(
            this.page,
            {
              deptId: data.id,
            },
            true
          );
        } else {
          this.handleClick(data);
        }
      } else {
        this.tableDataOrg.forEach((item, i) => {
          if (item.deptId == data.id) {
            this.tableDataOrg.splice(i, 1);
          }
        });
      }
    },

    // clickTreeDeal(curObj, objStatus) {
    //   console.log(curObj);
    //   console.log(objStatus);
    //   // curObj: 当前节点数据
    //   // objStatus： 当前节点的状态，选中为 true ,取消选择为false
    //   // this.$refs.tree.getNode(curObj)：获取当前节点的node
    //   if (objStatus) {
    //     // 当前节点选中，勾选父节点
    //     const parentNode = this.$refs.treeSelect.getNode(curObj).parent;
    //     if (parentNode.key !== undefined) {
    //       this.$refs.treeSelect.setChecked(parentNode, true);
    //     }
    //   } else {
    //     // 当前节点取消选中，所有子节点取消选中
    //     if (curObj.children !== undefined) {
    //       curObj.children.forEach((item, i) => {
    //         this.$refs.treeSelect.setChecked(item, false, true);
    //       });
    //     }
    //   }
    // },
    getRowKeys(row) {
        return row.username
      },
    //选人添加到右边的框
    handleClick(val) {
      // for (var i = 0; i < this.tableDataUser.length; i++) {
      //   if (this.tableDataUser[i].username == vm.username) {
      //     return;
      //   }
      // }
      //this.multipleSelection = val;

      if (this.lastPage == "ndcj") {
        this.tableDataUser = [];
        this.tableDataOrg = [];
        this.tableDataOrgSingle = [];
        this.$refs.treeSelect.setCheckedKeys([]);
      }
      let objUser 
      this.tableDataUser=[]
      for(var i in val){
        objUser = {
          hzId: this.qjGzId,
          deptName: val[i].deptName,
          deptId: val[i].deptId,
          userId: val[i].userId,
          lly: val[i].lly,
          username: val[i].username,
          ryName: val[i].ryName,
          type: val[i].type,
        };
        this.tableDataUser.push(objUser);
        this.unique(this.tableDataUser);
      }
      
      
    },
    //数组去重
    unique(arr) {
      for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
          if (arr[i].userId == arr[j].userId) {
            //第一个等同于第二个，splice方法删除第二个
            arr.splice(j, 1);
            j--;
          }
        }
      }
      return arr;
    },
    //删除人员list
    delUserList(index) {
      this.tableDataUser.splice(index, 1);
    },
    delOrgList(index, deptId) {
      if (this.lastPage == "ndts") {
        this.tableDataOrgSingle.splice(index, 1);
        this.tableDataOrg = this.tableDataOrg.filter(
          (item) => item.deptId != deptId
        );
      } else {
        this.tableDataOrg.splice(index, 1);
        this.tableDataOrgSingle.splice(index, 1);
      }
    },
    //清空记录
    clearDataList() {
      this.qjDeptId = "";
      this.tableDataDept = [];
      this.tableDataUser = [];
      this.tableDataOrg = [];
      this.tableDataOrgSingle = [];
    },
    //保存拟定推送
    btnSave() {
      this.$message.closeAll();
      console.log(this.checked1, this.checked2);
      if (
        this.tableDataOrg.length == 0 &&
        this.tableDataUser.length == 0 &&
        !this.checked1 &&
        !this.checked2 &&
        this.lastPage != "rwsndts"
      ) {
        this.$message.warning("请至少选择一条数据！");
        return false;
      } else if (this.lastPage == "ndcj" && this.tableDataOrg.length > 1) {
        this.$message.warning("只能选择一条数据！");
        return false;
      } else if (
        this.tableDataOrg.length == 0 &&
        this.tableDataUser.length == 0 &&
        this.lastPage == "rwsndts" &&
        !this.bkhr
      ) {
        this.$message.warning("请至少选择一条数据！");
        return false;
      }
      this.canSubmit = false;
      this.visible = false;
      var paramUser = [];
      for (var i = 0; i < this.tableDataUser.length; i++) {
        paramUser[i] = {
          userId: this.tableDataUser[i].userId,
          deptId: this.tableDataUser[i].deptId,
          deptName: this.tableDataUser[i].deptName,
          ryName: this.tableDataUser[i].ryName,
        };
      }
      const paramOrg = this.tableDataOrg.map((item) => {
        const temp = {};
        if (item) {
          temp.userId = item.userId;
          temp.deptId = item.deptId;
          temp.deptName = item.deptName;
          temp.ryName = item.ryName;
        }
        return temp;
      });
      const tgLx = paramOrg.length > 0 ? "1" : "2";
      var fayue = 0;
      var shouyue = 0;
      var bkhr = 0;
      if (this.bkhr) {
        bkhr = 1;
      }
      if (this.checked1) {
        fayue = 1;
      } else {
        fayue = 0;
      }
      if (this.checked2) {
        shouyue = 1;
      } else {
        shouyue = 0;
      }
      console.log(shouyue, fayue);
      var params = {
        ids: this.ids,
        tableDataUser: paramUser,
        selectorgdata: paramOrg,
        tgLx: tgLx,
        type: this.type,
        fayue,
        shouyue,
        bkhr,
      };
      this.$nextTick(() => {
        this.$emit("submitfy", params);
      });
    },
    // tree搜索事件,搜索人
    btnSearch() {
      let param = {
        deptId: this.qjDeptId,
      };

      if (this.listQuery.name.trim() !== "") {
        param["username"] = this.listQuery.name.trim();
        param["ryName"] = this.listQuery.name.trim();
      }
      this.getPageUsers(param);
    },
    // 分页
    // 每页数
    sizeChangeHandle(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1;
      this.getPageUsers();
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.currentPage = val;
      this.getPageUsers();
    },
    //分页刷新
    getPageUsers(vm) {
      if (vm) {
        this.getPersons(this.page, vm);
      } else {
        this.getPersons(this.page, {
          deptId: this.qjDeptId,
        });
      }
    },
    //取消按钮
    btnCancel() {
      this.visible = false;
      this.clearDataList();
    },
    //判空
    validatenull(val) {
      return validatenull(val);
    },
  },
};
</script>

<style scoped>
</style>
